package cn.com.common.job.task;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import cn.com.common.config.FileUploadProperties;
import cn.com.common.config.FileUploadProperties.FileRead;
import cn.com.common.constants.Constants;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasDeletePictureProcessTask")
@DisallowConcurrentExecution
public class GasDeletePictureProcessTask {

	@Value("${gasstation.timedTask.gasDeletePictureProcessTask}")
	private String gasDeletePictureProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private FileUploadProperties fileUploadProperties;

	public void run(String params) throws Exception {
		logger.debug("gasDeletePictureProcessTask定时任务正在执行，参数为：{}", params);

		logger.debug("application参数为gasDeletePictureProcessTask：{}", gasDeletePictureProcessTask);

		if (gasDeletePictureProcessTask.equals(Constants.JOB_STOP)) {

			logger.debug("application配置文件控制不执行gasDeletePictureProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasDeletePictureProcessTask定时任务");

		}

		int days = 180; // 默认180天
		if (TsBqUtils.isNotNull(params)) {
			String[] _paramsArr = params.split("_");
			for (String _params : _paramsArr) {
				deletePictureByDay(_params);
			}
			
		} else {
			LocalDate now = LocalDate.now();
			LocalDate thirtyDaysBefore = now.minusDays(days); // 减去days天
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
			// 使用 formatter 格式化 LocalDate
			String formattedDate = thirtyDaysBefore.format(formatter);
			deletePictureByDay(formattedDate);
		}

	}

	private void deletePictureByDay(String day) {
		logger.info("删除图片日期：" + day);

		List<String> pathList = new ArrayList<String>();
		List<FileRead> read = fileUploadProperties.getRead();
		if (TsBqUtils.isNotNull(read)) {
			for (FileRead fileRead : read) {
				String pathRead = fileRead.getPathRead();
				pathList.add(pathRead + day + "/");
			}
		}

		String path = fileUploadProperties.getPath();
		if (TsBqUtils.isNotNull(path)) {
			pathList.add(path + day + "/");
		}

		if (TsBqUtils.isNotNull(pathList)) {
			for (String _path : pathList) {
				countFiles(_path);
				deleteFolder(_path);
			}
		} else {
			logger.debug("gasDeletePictureProcessTask定时任务执行完成，pathList为空！");
		}
	}

	private void countFiles(String path) {
		File directory = new File(path);
		// 确保路径是目录
		if (directory.isDirectory()) {
			// 获取目录下的所有文件和文件夹
			File[] files = directory.listFiles();
			if (files != null) {
				int length = files.length;
				logger.info("gasDeletePictureProcessTask定时任务执行路径" + path + ",文件数：" + length);
			}
		} else {
			logger.info("gasDeletePictureProcessTask定时任务执行路径" + path + ",无此文件夹！");
		}
	}
	// 删除文件
	private boolean removeFiles(String path) {
		File file = new File(path);
		if (file.exists()) {
			return file.delete();
		} else {
			return false;
		}
	}
	// 删除文件夹
	public static void deleteFolder(String folderPath) {
        File folder = new File(folderPath);
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFolder(file.getPath());
                    } else {
                        file.delete();
                    }
                }
            }
            folder.delete();
        }
    }
	
}
